<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use think\facade\Db;
use app\common\model\Discuss as DiscussModel;

class Discuss extends BaseApi
{
    //随机获取话题列表
    public function random()
    {
        $list = Db::name('discuss')->orderRaw('rand()')->limit(6)->select()->toArray();
        return $this->data($list);
    }

    //话题列表
    public function list()
    {
        $keyword = input("keyword");
        $where = [];

        if ($keyword) {
            $where[] = ['title', "like", "%$keyword%"];
        }

        $list = DiscussModel::withJoin(['userInfo' => ['nickname', 'avatar']])->where($where)->paginate(10);
        return $this->data($list);
    }

    public function infoByTitle()
    {
        $title = input("title");

        $info = DiscussModel::where('title', $title)->find();

        if (empty($info)) {
            $disData["user_id"] = $this->getUserId();
            $disData["title"] = $title;

            $info = DiscussModel::create($disData);
            $info->see_num = 1;
        }

        Db::name('discuss')->where('id', $info->id)->inc('see_num')->update();

        return $this->data($info);
    }
}